import 'package:fluro/fluro.dart';
import 'package:flutter/widgets.dart';
import 'package:imperius_insights/entity/hr.dart';
import 'package:imperius_insights/events/event-bus.dart';
import 'package:imperius_insights/events/scope-changed-event.dart';
import 'package:imperius_insights/portal/state/indicator/indicator.dart';
import 'package:imperius_insights/portal/state/mobx/store.dart';
import 'package:mobx/mobx.dart';
import 'package:provider/provider.dart';

import 'domain.dart';

part 'view_model_humans.g.dart';

class ViewModel = _ViewModelInternal with _$ViewModel;

abstract class _ViewModelInternal with Store, StoreWithLifecycle {
  @observable
  IndicatorState<List<HumanResource>> humans;

  @observable
  String currentSysName;

  _ViewModelInternal();

  @override
  onContextAttached(BuildContext context) {
    super.onContextAttached(context);
    humans = IndicatorState<List<HumanResource>>();
    refresh();
  }

  @override
  onContextDetached(BuildContext context) {
    super.onContextDetached(context);
  }

  onSelect(HumanResource human) async {
    await Provider.of<Domain>(context, listen: false).saveScopeHumanId(human.sysName);
    runInAction(() => this.currentSysName = human.sysName);
    defaultEventBus.fire(ScopeChangedEvent());
    final router = Provider.of<Router>(context, listen: false);
    router.pop(context);
  }

  Future<void> refresh() async {
    final domain = Provider.of<Domain>(context, listen: false);
    final departmentId = await domain.getDepartmentId();
    final currentSysName = await domain.getScopeHumanId();
    runInAction(() => this.currentSysName = currentSysName);
    this.humans.fireFetch(() async {
      final humans = await domain.queryHumansByDepartment(departmentId);
      humans.removeWhere((h) => h.sysName == 'meng.jiang');
      return humans;
    });
  }
}
